package main

import (
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup

// 向 intChan 放入 1-120000个数
// 从 intChan 取出数据并判断是否为素数，如果是，就把得到的素数放在primeChan
// 从 primeChan 取出数据并打印

func intNum(ch chan int, total int) {
	for i := 1; i <= total; i++ {
		ch <- i
	}
	close(ch)
	wg.Done()
}

func primeNum(ichan chan int, pchan chan int, echan chan int) {
	for v := range ichan {
		var i = 2
		for ; i < v; i++ {
			if v%i == 0 {
				break
			}
		}
		if i == v {
			pchan <- i
		}
	}
	echan <- 0
	if len(echan) == 16 {
		close(pchan)
		close(echan)
	}
	wg.Done()
}

func printPrime(pchan chan int) {
	for v := range pchan {
		fmt.Printf("素数：%v\n", v)
	}
	wg.Done()
}

func main() {
	var startTime = time.Now()

	var intChan = make(chan int, 100)
	var primeChan = make(chan int, 100)
	var exitChan = make(chan int, 16)

	wg.Add(1)
	go intNum(intChan, 100000)
	for i := 0; i < 16; i++ {
		wg.Add(1)
		go primeNum(intChan, primeChan, exitChan)
	}
	wg.Add(1)
	go printPrime(primeChan)
	wg.Wait()
	fmt.Println("程序结束")
	fmt.Printf("耗时：%v\n", time.Now().Sub(startTime))
	for v := range exitChan {
		fmt.Print(v)
	}
}
